# -*- coding:utf-8 -*-
import VBAPI
from win32com import client
import traceback

CREO_APP = 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe'
INPUT_DIR = 'E:/python/test_data/'
filename = 'sxio.asm'
drwname = 'sxrl-0100.drw'
formatename = 'D:/PTC/config/format/a3_h.frm'

#获取模型列表 递归
def get_modellist(Isession, filename):
    #检索模型
    ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
    mdlDescr = ModelDescriptor.CreateFromFileName(filename)
    RetriveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
    options = RetriveModelOptions.Create()
    options.AskUserAboutReps = False
    model = Isession.RetrieveModelWithOpts(mdlDescr, options)
    #获取模型列表
    items = model.ListFeaturesByType(True, getattr(VBAPI.constants, 'EpfcFEATTYPE_COMPONENT'))
    for item in items:
        item_Descr = item.ModelDescr
        print(item_Descr.GetFileName())
        if item_Descr.GetExtension() == 'asm':
            get_modellist(Isession, item_Descr.GetFileName())

#替换绘图模板
def change_formate(Isession, drwname, formatename):
    # 检索模型
    ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
    mdlDescr = ModelDescriptor.CreateFromFileName(drwname)
    RetriveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
    options = RetriveModelOptions.Create()
    options.AskUserAboutReps = False
    sheetOwner = Isession.RetrieveModelWithOpts(mdlDescr, options)
    #获取SheetNumber
    sheetNumber = sheetOwner.CurrentSheetNumber

    #打开图框
    ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
    mdlDescr = ModelDescriptor.CreateFromFileName(formatename)
    RetriveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
    options = RetriveModelOptions.Create()
    options.AskUserAboutReps = False
    formatOwner = Isession.RetrieveModelWithOpts(mdlDescr, options)
    sheetOwner.Display()
    #删除表格
    tables = sheetOwner.ListTables()
    for table in tables:
        sheetOwner.DeleteTable(table, False)
    #设置图框
    sheetOwner.SetSheetFormat(sheetNumber, formatOwner, None, None)
    sheetOwner.RegenerateSheet(sheetNumber)
    sheetOwner.Save()

if __name__ == '__main__':
    # 后台打开软件
    cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
    AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
    Isession = AsyncConnection.Session
    # 更改工作目录
    Isession.ChangeDirectory(INPUT_DIR)
    try:
        #get_modellist(Isession, filename)
        change_formate(Isession, drwname, formatename)
    except Exception as e:
        print(e)
        print(traceback.print_exc())
    finally:
        AsyncConnection.End()





